<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Product Quantity Record");
$page_title=__("Product Quantity Record");

if(!$pv["task"]["Inventory Record"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to access inventory record."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

$item_per_page=100;//$vars['admin_item_per_page'];

//#####INVENTORY GET#####
if($_GET["refno"]){
	if(!$get_s["refno"]){
		$errmsg.=__("Invalid product ID provided.")."<br />\n";
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->products where refno='$get_d[refno]'"))){
		$errmsg.=replace_tag(__("Product with Reference No. '<%refno%>' does not exist in the system."), array("<%refno%>"=>$get_h["refno"]))."<br />\n";
	}
	if(!in_array($get_s['qty_type'], array('all','in','out'))){
		$errmsg.=__("Please select a quantity type.")."<br />";
	}
	if(strlen($get_s['date_from'])){
		if(!verify_date($get_s['date_from'])){
			$errmsg.=__("Please provide a valid date in the date from.")."<br />";
		}else{
			$from_time = strtotime($get_s['date_from']);
			if(strlen($get_s['date_to'])){
				if(!verify_date($get_s['date_to'])){
					$errmsg.=__("Please provide a valid date in the date to.")."<br />";
				}else{
					$to_time = strtotime($get_s['date_to']);
					if($from_time > $to_time){
						$errmsg.=__("The from date cannot be later than the to date.")."<br />";
					}
				}
			}
		}
	}

	if(!$errmsg){
		$prod = mysql_fetch_assoc($r);
		if($get_s['qty_type'] == 'in'){
			$qty_type_q = "type='c'";
		}elseif($get_s['qty_type'] == 'out'){
			$qty_type_q = "type='d'";
		}else{
			$qty_type_q = "1=1";
		}
		if($get_s['type_admin']){
			$type_q .= "'a',";
		}
		if($get_s['type_ms']){
			$type_q .= "'m','n',";
		}
		if($get_s['type_ss']){
			$type_q .= "'s','t',";
		}
		$type_q = rtrim($type_q, ',');
		if($type_q){
			$type_q = "ttype in ($type_q)";
		}else{
			$type_q = "1=1";
		}
		if(strlen($from_time)){
			$from_date = date('Y-m-d', $from_time).' 00:00:00';
			if(strlen($to_time)){
				$to_date = date('Y-m-d', $to_time).' 23:59:59';
			}else{
				$to_date = date('Y-m-d', $from_time).' 23:59:59';
			}
			$date_q = "cdate>='$from_date' and cdate<='$to_date'";
		}else{
			$date_q = "1=1";
		}
		
		$count_sql = "select count(*) from $db->prod_qty_record where pid='$prod[id]' and $qty_type_q and $type_q and $date_q";
		$record_sql = "select * from $db->prod_qty_record where pid='$prod[id]' and $qty_type_q and $type_q and $date_q order by cdate desc limit <%limit_start%>, <%limit%>";
		$in_sql = "select sum(qty) from $db->prod_qty_record where pid='$prod[id]' and ".($qty_type_q == '1=1' || $qty_type_q == "type='c'"? "type='c'" : "1=2")." and $type_q and $date_q";
		$out_sql = "select sum(qty) from $db->prod_qty_record where pid='$prod[id]' and ".($qty_type_q == '1=1' || $qty_type_q == "type='d'"? "type='d'" : "1=2")." and $type_q and $date_q";
		$cur_page=$_GET["nav"];
		$total_record=@mysql_result(mysql_query($count_sql), 0);
		$total_page=ceil($total_record/$item_per_page);
		$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
		$limit_start=($page-1)*$item_per_page;
		$nav_link=format_page_admin($page, $total_page, $this_file);
		$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
		$k=0;
		$total_in = ($q = mysql_result(mysql_query($in_sql), 0))? $q : 0;
		$total_out = ($q = mysql_result(mysql_query($out_sql), 0))? $q : 0;
		for($i=0;$i<$this_page_total;$i++){
			$run_no = (($page - 1) * $item_per_page) + $i + 1;
			$qty=mysql_fetch_assoc($r);
			if($qty['ttype'] == 'a'){//admin update qty
				$action_descr = 'Quantity updated by admin';
			}elseif($qty['ttype'] == 'm'){//admin / stockist add member sales
				$sale = mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$qty[sid]' limit 1"));
				$action_descr = "Quantity deducted for member sales ID #$sale[id], member ID #$sale[uid]";
			}elseif($qty['ttype'] == 'n'){//admin / stockist cancel member sales
				$sale = mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$qty[sid]' limit 1"));
				$action_descr = "Quantity credited for cancelled member sales ID #$sale[id], member ID #$sale[uid]";
			}elseif($qty['ttype'] == 's'){//admin add stockist sales
				$sale = mysql_fetch_assoc(mysql_query("select * from $db->stockist_sales where id='$qty[sid]' limit 1"));
				$action_descr = "Quantity deducted for stockist sales ID #$sale[id], stockist ID #$sale[sid]";
			}elseif($qty['ttype'] == 't'){//admin cancel stockist sales
				$sale = mysql_fetch_assoc(mysql_query("select * from $db->stockist_sales where id='$qty[sid]' limit 1"));
				$action_descr = "Quantity credited for cancelled stockist sales ID #$sale[id], stockist ID #$sale[sid]";
			}
			$qty_row.="
			<tr class='row$k'>
				<td>$run_no</td>
				<td>$action_descr</td>
				<td>".(in_array($qty['ttype'], array('m','n'))? "<a href='{$vars['file']['admin']['add_edit_sales']}?type=edit&id=$sale[id]' target='_blank'>$sale[id]</a>" : 'N/A')."</td>
				<td>".(in_array($qty['ttype'], array('s','t'))? "<a href='{$vars['file']['admin']['add_edit_stockist_sale']}?type=edit&id=$sale[id]' target='_blank'>$sale[id]</a>" : 'N/A')."</td>
				<td>".($qty['type'] == 'c'? $qty['qty'] : '0')."</td>
				<td>".($qty['type'] == 'd'? $qty['qty'] : '0')."</td>
				<td width='130'>".date($vars["system_date_format"], strtotime($qty["cdate"]))."</td>
			</tr>";
			$k=1-$k;
		}
		
		//listing text
		$listing_text=replace_tag(__("Listing <%x%> quantity records."), array("<%x%>"=>strval($total_record)));
		
		//total in/out
		$total_in_out = "<p class='bold'>".__("Total In").": ".$total_in."<br />".__("Total Out").": ".$total_out."<br />".__("Balance").": ".($total_in - $total_out)."</p>";

		//listing
		$qty_list=
		"$total_in_out
		$listing_text $nav_link
		<table class='aml_table'>
			<tr class='aml_header'>
				<td>".__("No")."</td>
				<td>".__("Description")."</td>
				<td>".__("MSID")."</td>
				<td>".__("SSID")."</td>
				<td>".__("In")."</td>
				<td>".__("Out")."</td>
				<td>".__("Date")."</td>
			</tr>
			$qty_row
		</table>
		$nav_link
		$total_in_out";
		//#####END QUANTITY LIST#####
	}
	$errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}

//javascript
ob_start();
?>
<script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.datepicker.js"); ?>'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
	j('select[@name=type]').change(function(){
		j('form[@name=comm_form]').submit();
	});
	
	<?php #datepicker ?>
	j('#date_from').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,5,1), 
		maxDate: '+1M +10D'
	});
	j('#date_to').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,5,1), 
		maxDate: '+1M +10D'
	});
});
</script>
<?php
$jvscript = ob_get_clean();

//css
ob_start();
?>
<link rel="stylesheet" href="<?php echo CSS_URL; ?>/jstheme/ui-lightness/jquery-ui.css" type="text/css" />
<?php
$css .= ob_get_contents();
ob_end_clean();

//listing
$prod_qty_list=($errmsg || $msg? $errmsg.$msg : "")."
<form name='qty_form' method='get' action='$this_file".($_SERVER["QUERY_STRING"]? "?".$_SERVER["QUERY_STRING"] : "")."'>
".__("Product Code").": <input type='text' name='refno' value=\"$get_h[refno]\" /> <input type='submit' value=\"".__("Submit")."\" /><br />
".__("Quantity Type").": <input type='radio' name='qty_type' value='all' ".($get_s['qty_type'] == 'all' || !isset($get_s['qty_type'])? "checked='checked'" : '')." id='q_all' /> <label for='q_all'>".__("Both")."</label>
<input type='radio' name='qty_type' value='in' ".($get_s['qty_type'] == 'in'? "checked='checked'" : '')." id='q_in' /> <label for='q_in'>".__("In Only")."</label>
<input type='radio' name='qty_type' value='out' ".($get_s['qty_type'] == 'out'? "checked='checked'" : '')." id='q_out' /> <label for='q_out'>".__("Out Only")."</label><br />

".__("Transaction Type").": <input type='checkbox' name='type_admin' ".($get_s['type_admin']? "checked='checked'" : '')." id='t_admin' /> <label for='t_admin'>".__("Admin")."</label>
<input type='checkbox' name='type_ms' ".($get_s['type_ms']? "checked='checked'" : '')." id='t_ms' /> <label for='t_ms'>".__("Member Sales")."</label>
<input type='checkbox' name='type_ss' ".($get_s['type_ss']? "checked='checked'" : '')." id='t_ss' /> <label for='t_ss'>".__("Stockist Sales")."</label> <span class='italic'>(".__("Leave blank to include all options").")</span><br />

".__("Date Range").": <input type='text' name='date_from' id='date_from' value=\"".$get_h['date_from']."\" /> to <input type='text' name='date_to' id='date_to' value=\"".$get_h['date_to']."\" />
</form><br />\n
$qty_list";

$content="<h2>$page_title</h2>$prod_qty_list";

print format_admin_page($content, $this_title, $css . $jvscript);
?>